package com.gimi.cloud.bbp.commonService.sms.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.gimi.cloud.bbp.common.constant.RedisKeyConstant;
import com.gimi.cloud.bbp.common.utils.JsonUtil;
import com.gimi.cloud.bbp.commonService.redis.RedisService;
import com.gimi.cloud.bbp.commonService.sms.SmsService;
import com.gimi.cloud.bbp.dto.sys.AlidayuDTO;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 短信发送接口
 * @author wbj
 * @version 1.0
 * @Description
 * @create 2018-01-24
 **/
@Service
public class SmsServiceImpl implements SmsService{
    private static final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);
    private RedisService redisService;

    @Autowired
    public SmsServiceImpl(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public boolean sendMsgByAliYun(AlidayuDTO alidayuDto) throws ClientException {
        JSONObject smsConfig = redisService.getJSONObjectConfigByKey(RedisKeyConstant.CONFIG_KEY_APP_SMS);
        if(null == smsConfig){
            return false;
        }
        smsConfig = smsConfig.getJSONObject("AliYun");
        System.setProperty("sun.net.client.defaultConnectTimeout",smsConfig.getString("defaultConnectTimeout"));
        System.setProperty("sun.net.client.defaultReadTimeout", smsConfig.getString("defaultReadTimeout"));
        String result = "error";
        AlidayuDTO alidayuConfig = new AlidayuDTO();
        alidayuConfig.setAccessKeyId(smsConfig.getString("accessKeyId"));
        alidayuConfig.setAccessKeySecret(smsConfig.getString("accessKeySecret"));
        alidayuConfig.setSign(smsConfig.getString("sign"));
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", alidayuConfig.getAccessKeyId(), alidayuConfig.getAccessKeySecret());
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", smsConfig.getString("product"), smsConfig.getString("domain"));
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号18880443285
        request.setPhoneNumbers(alidayuDto.getPhone());
        //必填:短信签名-可在短信控制台中找到 给米钱包
        request.setSignName(alidayuConfig.getSign());
        //必填:短信模板-可在短信控制台中找到 SMS_10990892
        request.setTemplateCode(alidayuDto.getTemplate());
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 "{\"name\":\"Tom\", \"code\":\"123\"}"
        request.setTemplateParam(alidayuDto.getParams());
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = null;
        try{
            sendSmsResponse = acsClient.getAcsResponse(request);
            logger.info("阿里云通信短信发送结果：" + JsonUtil.toJson(sendSmsResponse) + "\n");
            if(sendSmsResponse != null ){
                if(sendSmsResponse.getCode() != null && "OK".equalsIgnoreCase(sendSmsResponse.getCode())){
                    return true;
                }
            }
        }catch (Exception e){
            logger.info("阿里大于短信发送异常");
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean sendMsgByAliDayu(AlidayuDTO alidayuDTO) throws Exception {
        if(null == alidayuDTO || StringUtils.isAnyBlank(alidayuDTO.getPhone())){
            return false;
        }
        JSONObject smsConfig = redisService.getJSONObjectConfigByKey(RedisKeyConstant.CONFIG_KEY_APP_SMS);
        if(null == smsConfig){
            return false;
        }
        smsConfig = smsConfig.getJSONObject("AliDaYu");
        TaobaoClient client = new DefaultTaobaoClient(smsConfig.getString("alidayuUrl"), smsConfig.getString("alidayuKey"), smsConfig.getString("alidayuSecret"));
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        //短信签名，传入的短信签名必须是在阿里大于“管理中心-短信签名管理”中的可用签名。如“阿里大于”已在短信签名管理中通过审核，则可传入”阿里大于“（传参时去掉引号）作为短信签名。短信效果示例：【阿里大于】欢迎使用阿里大于服务。
        req.setSmsFreeSignName(smsConfig.getString("alidayuSign"));
        req.setSmsTemplateCode(alidayuDTO.getTemplate());
        req.setSmsType(smsConfig.getString("alidayuSmsType"));
        req.setSmsParamString(alidayuDTO.getParams());
        //收件人
        req.setRecNum(alidayuDTO.getPhone());
        try {
            AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
            String res = String.valueOf(rsp.getBody());
            logger.info("阿里大于短信发送结果："+res);
            if(JsonUtil.isJSON(res)){
                JSONObject jsonObj = JsonUtil.jsonToJSONObject(res);
                //发送成功
                if(jsonObj.containsKey("alibaba_aliqin_fc_sms_num_send_response")){
                    jsonObj = jsonObj.getJSONObject("alibaba_aliqin_fc_sms_num_send_response").getJSONObject("result");
                    if("true".equals(jsonObj.getString("success"))){
                        return true;
                    }
                }else if(jsonObj.containsKey("error_response")){
                    logger.info("阿里大于短信发送失败："+jsonObj.getJSONObject("error_response"));
                }
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return false;
    }
}
